package cn.tedu.ivos.vehicle.service.impl;

import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleSaveParam;
import cn.tedu.ivos.vehicle.pojo.entity.Vehicle;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import cn.tedu.ivos.vehicle.service.VehicleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class VehicleServiceImpl implements VehicleService {
    @Autowired
    VehicleMapper vehicleMapper;

    @Override
    public List<VehicleVO> selectVehicle(VehicleQuery vehicleQuery) {
        List<VehicleVO> vehicleVOList = vehicleMapper.selectVehicle(vehicleQuery);
        return vehicleVOList;
    }

    @Override
    public void saveVehicle(VehicleSaveParam vehicleSaveParam) {
        log.debug("保存车辆业务:vehicleSaveParam={}", vehicleSaveParam);
        Vehicle vehicle = new Vehicle();
        BeanUtils.copyProperties(vehicleSaveParam, vehicle);
        if (vehicle.getId() == null) {
            // 新增车辆初始状态为空闲
            vehicle.setStatus("1");
            vehicle.setGeofenceBindStatus("0");
            // 新增时间
            vehicle.setCreateTime(new Date());
            vehicleMapper.saveVehicle(vehicle);
        } else {
            // 更新时间
            vehicle.setUpdateTime(new Date());
            vehicleMapper.updateVehicle(vehicle);
        }
    }

    @Override
    public void deleteVehicle(Long id) {
        log.debug("删除车辆业务:id={}", id);
        vehicleMapper.deleteVehicle(id);
    }

    @Override
    public void unbindVehicle(Long id) {
        log.debug("车辆解绑围栏业务:id={}", id);
        Vehicle vehicle = new Vehicle();
        vehicle.setId(id);
        vehicle.setGeofenceBindStatus("0");
        // 原Update方法映射的动态SQL语句中 要求不为null才可进行更新 因此此处显式插入null值时需要在mapper层使用新逻辑
        vehicle.setGeofenceId(null);
        vehicle.setUpdateTime(new Date());
        vehicleMapper.updateNullValue(vehicle);
    }

    @Override
    public void bindVehicle(Long id, Long geoId) {
        log.debug("车辆绑定业务:id={},geoId={}", id, geoId);
        Vehicle vehicle = new Vehicle();
        vehicle.setId(id);
        vehicle.setGeofenceBindStatus("1");
        vehicle.setGeofenceId(geoId);
        vehicle.setUpdateTime(new Date());
        vehicleMapper.updateVehicle(vehicle);
    }
}
